package io.yizoo.core.message;

import io.yizoo.business.entity.biz_hrm_ei_basic;
import io.yizoo.system.entity.sys_user_third;
import io.yizoo.system.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

public abstract class AbstractMessageService implements MessageService {

    @Autowired
    public io.elm.core.Ctor Ctor;

    @Override
    public abstract String sendMsg(MessageContext context);

    protected void validParam(MessageContext context) {
        String sendUserId = context.getSendUserId();
        if (StringUtil.isEmpty(sendUserId)) {
            throw new RuntimeException("请输入发送人员");
        }
        String title = context.getTitle();
        if (title == null) {
            throw new RuntimeException("请输入发送标题");
        }
        if (title.length() >= 100) {
            throw new RuntimeException("发送内容不能超过100个字节");
        }
        String content = context.getContent();
        if (content == null) {
            throw new RuntimeException("请输入发送内容");
        }
        if (content.length() >= 1000) {
            throw new RuntimeException("发送内容不能超过1000个字节");
        }
        Boolean isAll = context.getAll();
        if (!isAll) {
            List<String> userIdList = context.getUserIdList();
            if (userIdList == null) {
                throw new RuntimeException("请输入接收人员");
            }
            if (userIdList.size() > 100) {
                throw new RuntimeException("接收人员不能超过100个");
            }
        }
    }

    protected String getTargetUserIdListStr(MessageContext context) {
        String toTargetStr = "";
        List<String> userIdList = context.getUserIdList();
        String userIdListStr = StringUtils.join(userIdList, ",");
        userIdListStr = "'" + userIdListStr + "'";
        List<?> ret = Ctor.CoreMapper.USelect(
                Ctor.DMaker()
                        .Selector
                        .From(sys_user_third.class)
                        .Where("and user_id in (" + userIdListStr + ")")
                        .GetFactor());
        if (CollectionUtils.isEmpty(ret)) {
            throw new RuntimeException("发送人员不存在");
        }
        StringJoiner stringJoiner = new StringJoiner("|");
        for (Object o : ret) {
            if (o == null) {
                continue;
            }
            if (o instanceof Map) {
                Map map = (Map) o;
                stringJoiner.add(map.get("third_id").toString());
            }
            toTargetStr = stringJoiner.toString();
        }
        return toTargetStr;
    }
}
